import * as CryptoJS from 'crypto-ts';
import FingerprintJS from '@fingerprintjs/fingerprintjs';

const KEY = 'fingerprint';
const secretKey = 'hulingwtp12341234'; //项目前后端统一(安全系数低)

/**
 * 初始化浏览器指纹
 */
const initFingerprint = async () => {
  try {
    //获取设备唯一标识
    const fp = await FingerprintJS.load();
    const result = await fp.get();
    const visitorId = result.visitorId;
    // 暂时不加密
    // const encryptedFP = encryptedFingerprint(fingerprint);
    localStorage.setItem(KEY, visitorId);
    return visitorId;
  } catch (error) {
    console.error('Get fingerprint ERROR: ', error);
    return null;
  }
};

/**
 * 对已有的浏览器指纹进行加密
 * @param {string} _fingerprint
 * @returns
 */
export const encryptedFingerprint = (_fingerprint: string) => {
  const key = CryptoJS.enc.Utf8.parse(secretKey); //处理密钥
  const srcs = CryptoJS.enc.Utf8.parse(_fingerprint); //处理要加密的字符串
  const dd = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.PKCS7,
  });
  return dd.toString();
};

/**
 * 获取指纹
 * @returns
 */
export const getFingerprint = async () => {
  const fingerprint = localStorage.getItem(KEY);
  if (fingerprint) {
    return fingerprint;
  }
  return await initFingerprint();
};
